#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Mikan RSS View Module

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_7"
__date__    = "2014/05/05"
__license__ = 'LGPL'
# ------------------------------------------------------------
## Import Section
# ------------------------------------------------------------
# Python
import traceback

# ping
import ping

# ESiPC
from esipc import ESiPCProperty

# Mikan
from mikan.view import MikanJSONView

# ------------------------------------------------------------
## Variable Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Mikan Contant
# ------------------------------------------------------------

# ------------------------------------------------------------
## Function Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Class Section
# ------------------------------------------------------------

class MikanPingJSONView(MikanJSONView):

	def set_timeout(self, value):
		self.FTimeout = value

	def get_timeout(self):
		return self.FTimeout

	def get_items(self):
		return self.FItems

	def __init__(self, request, items=None, timeout=2):
		super(MikanPingJSONView, self).__init__(request)

		self.FItems = items
		if items == None:
			self.FItems = []
		self.FTimeout = timeout

	def perform(self):
		jsons = []
		items = []

		for name, address in self.items:
			r = None
			try:
				r = ping.do_one(address, self.timeout, 64)
			except:
				self.logger.error(traceback.format_exc())

			item = {}
			item["host"] = name
			item["address"] = address
			if r != None:
				item["result"] = u"%0.4fms" % r
			else:
				item["result"] = u"-"

			items.append(item)

		self.result = { "items": items }

		return super(MikanPingJSONView, self).perform()

	# ----------------------------------------------------
	## Property
	timeout = ESiPCProperty(get_timeout, set_timeout, None)
	items = ESiPCProperty(get_items, None, None)

# ------------------------------------------------------------
## Main Section
# ------------------------------------------------------------

# ------------------------------------------------------------
